/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.serli.sample.person.model.data.session;

import com.serli.sample.person.model.data.Person;
import com.serli.sample.person.model.data.persistence.PersonEntity;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Stateless;

/**
 *
 * @author serli
 */
@Stateless( name = "PeopleBean")
@Local(value={PeopleBeanLocal.class})
public class PersonBean extends SessionBeanParent implements PeopleBeanLocal {

    @Override
    public void insert(Person person) {
        transactionBegin();
        manager.persist(new PersonEntity(person));
        transactionCommit();
    }
    
    @Override
    public void delete(Person person) {
        transactionBegin();
        manager.remove(new PersonEntity(person));
        transactionCommit();
    }
    
    @Override
    public List<Person> getAllOrderByFirstName() {
        List<PersonEntity> entities = manager.createNamedQuery(PersonEntity.QUERY_FIND_ALL_ORDER_BY_FIRSTNAME).getResultList();
        return toListOfPerson(entities);
    }

    private List<Person> toListOfPerson(List<PersonEntity> entities) {
        List<Person> people = new ArrayList<Person>();
        if (entities != null && entities.size() > 0) {
            for (PersonEntity entity : entities) {
                people.add(getPersonObject(entity));
            }
        }
        return people;
    }

    public Person getPersonObject(PersonEntity entity) {
        return new Person(entity.getId(),
                entity.getFirstName(),
                entity.getLastName(),
                entity.getBirthDate(),
                entity.getGender());
    }
}